<?php
require_once __DIR__ . '/../../functions.php';

header('Content-Type: application/json');

// 检查管理员权限
if (!isAdmin()) {
    echo json_encode(['success' => false, 'message' => '您没有权限执行此操作']);
    exit;
}

// 验证输入
$username = $_POST['username'] ?? '';
$phone = $_POST['phone'] ?? '';
$password = $_POST['password'] ?? '';
$is_admin = intval($_POST['is_admin'] ?? 0);

if (empty($username) || empty($phone) || empty($password)) {
    echo json_encode(['success' => false, 'message' => '请填写完整信息']);
    exit;
}

if (strlen($password) < 6) {
    echo json_encode(['success' => false, 'message' => '密码长度不能少于6位']);
    exit;
}

if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
    echo json_encode(['success' => false, 'message' => '手机号格式不正确']);
    exit;
}

$db = getDB();

// 检查用户名是否已存在
$stmt = $db->prepare("SELECT id FROM users WHERE username = ?");
$stmt->execute([$username]);
if ($stmt->fetch()) {
    echo json_encode(['success' => false, 'message' => '该用户名已被使用']);
    exit;
}

// 检查手机号是否已存在
$stmt = $db->prepare("SELECT id FROM users WHERE phone = ?");
$stmt->execute([$phone]);
if ($stmt->fetch()) {
    echo json_encode(['success' => false, 'message' => '该手机号已被注册']);
    exit;
}

// 创建用户
$hashedPassword = passwordHash($password);
$stmt = $db->prepare("INSERT INTO users (phone, username, password, is_admin, status) VALUES (?, ?, ?, ?, 1)");

if ($stmt->execute([$phone, $username, $hashedPassword, $is_admin])) {
    echo json_encode(['success' => true, 'message' => '用户创建成功']);
} else {
    echo json_encode(['success' => false, 'message' => '用户创建失败']);
}